package com.zyx.groovydemo.closure
/**
 * @author zyx
 * @since 2022/5/8 00:33
 * desc: 闭包进阶使用
 *          闭包中三个重要变量: this, owner, delegate
 */
def scriptClosure = {
    // this: 带包闭包定义处的类
    println "scriptClosure this:" + this
    // owner: 代表闭包定义处的类或者对象
    println "scriptClosure owner:" + owner
    // delegate: 代表任意对象
    println "scriptClosure delegate:" + delegate
}

// scriptClosure.call()

// 定义了一个内部类
class Person {
    def static classClosure = {
        // this: 带包闭包定义处的类
        println "scriptClosure this:" + this
        // owner: 代表闭包定义处的类或者对象
        println "scriptClosure owner:" + owner
        // delegate: 代表任意对象
        println "scriptClosure delegate:" + delegate
    }

    def static say() {
        def classClosure = {
            // this: 带包闭包定义处的类
            println "scriptClosure this:" + this
            // owner: 代表闭包定义处的类或者对象
            println "scriptClosure owner:" + owner
            // delegate: 代表任意对象
            println "scriptClosure delegate:" + delegate
        }
        classClosure.call()
    }
}
// 指向类
// Person.classClosure.call()
// Person.say()

class Person2 {
    def classClosure = {
        // this: 代表闭包定义处的类
        println "scriptClosure this:" + this
        // owner: 代表闭包定义处的类或者对象
        println "scriptClosure owner:" + owner
        // delegate: 代表任意对象
        println "scriptClosure delegate:" + delegate
    }

    def say() {
        def classClosure = {
            // this: 代表闭包定义处的类
            println "scriptClosure this:" + this
            // owner: 代表闭包定义处的类或者对象
            println "scriptClosure owner:" + owner
            // delegate: 代表任意对象
            println "scriptClosure delegate:" + delegate
        }
        classClosure.call()
    }
}
// 指向对象
Person2 p = new Person2()
// p.classClosure.call()
// p.say()

// 闭包中定义一个闭包
def nestClosure = {
    def innerClosure = {
        // this: 代表闭包定义处的类
        println "scriptClosure this:" + this
        // owner: 代表闭包定义处的类或者对象
        println "scriptClosure owner:" + owner
        // delegate: 代表任意对象
        println "scriptClosure delegate:" + delegate
    }
    innerClosure.delegate = p // 修改默认的delegate
    innerClosure.call()
}
nestClosure.call()

/**
 * 闭包的委托策略
 */
class Student {
    String name
    def pretty = { "My name is ${name}" }

    String toString() {
        pretty.call()
    }
}

class Teacher {
    String name
}

def stu = new Student(name: 'Sarash')
def tea = new Teacher(name: 'Qndroid')
stu.pretty.delegate = tea
// 指定委托策略
//  Closure.DELEGATE_ONLY: 仅包含DELEGATE, 即使有OWNER了也以DELEGATE为主
//  Closure.DELEGATE_FIRST: DELEGATE优先, 此时如果有OWNER了则会被覆盖



stu.pretty.resolveStrategy = Closure.DELEGATE_ONLY
println stu.toString()
